package com.spring.shopping.controller;

import com.spring.shopping.entity.Product;
import com.spring.shopping.entity.User;
import com.spring.shopping.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductService productService;

    @GetMapping("/list")
    public String productList(Model model) {
        model.addAttribute("products", productService.getAllProducts());
        return "product/list";
    }

    @GetMapping("/detail")
    public String productDetail(@RequestParam("id") Integer id, Model model) {
        Product product = productService.getProductById(id);
        if (product == null) {
            return "redirect:/product/list";
        }
        model.addAttribute("product", product);
        return "product/detail";
    }

    @GetMapping("/post")
    public String showPostForm(Model model) {
        model.addAttribute("product", new Product());
        return "product/post";
    }

    @PostMapping("/post")
    public String postProduct(@ModelAttribute Product product,
                              @RequestParam("imageFile") MultipartFile imageFile,
                              HttpSession session) throws IOException {
        User user = (User) session.getAttribute("currentUser");
        if (user == null) {
            return "redirect:/user/login";
        }

        if (!imageFile.isEmpty()) {
            String fileName = UUID.randomUUID().toString() + "_" + imageFile.getOriginalFilename();
            String uploadDir = session.getServletContext().getRealPath("/resources/uploads/");
            File uploadPath = new File(uploadDir);
            if (!uploadPath.exists()) {
                uploadPath.mkdirs();
            }
            imageFile.transferTo(new File(uploadPath, fileName));
            product.setImagePath("/resources/uploads/" + fileName);
        }

        product.setUserId(user.getId());
        product.setStatus(1); // 上架状态
        productService.addProduct(product);
        return "redirect:/product/list";
    }

    @GetMapping("/category/{category}")
    public String productsByCategory(@PathVariable String category, Model model) {
        model.addAttribute("products", productService.getProductsByCategory(category));
        model.addAttribute("category", category);
        return "product/list";
    }
}